#!/bin/env/python3
import datetime
import time

from flask import render_template, request, jsonify, current_app, session, redirect, g

from . import admin_blue
from ... import db, constants
from ...models import User, News, Category
from ...utils import image_storage
from ...utils.commons import user_login_data
from ...utils.response_code import RET


@admin_blue.route('/logout')
def logout():
    session.pop("user_id", None)
    session.pop("is_admin", None)
    return redirect('/admin/login')


@admin_blue.route('/add_category', methods=['POST'])
def add_category():
    cate_id = request.json.get("id")
    cate_name = request.json.get("name")
    if not cate_name:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    if cate_id:
        try:
            cate = Category.query.get(cate_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="分类获取失败")
        if not cate:
            return jsonify(errno=RET.NODATA, errmsg="分类不存在")
        cate.name = cate_name

    else:
        cate = Category()
        cate.name = cate_name
        try:
            db.session.add(cate)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="分类创建失败")
    return jsonify(errno=RET.OK, errmsg="操作成功")


@admin_blue.route('/news_type')
def news_type():
    # 获取所有的分类对象
    try:
        news_category = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/news_type.html", errmsg="获取分类失败")
    cate_list = []
    for item in news_category:
        cate_list.append(item.to_dict())
    print(cate_list)
    return render_template("admin/news_type.html", cate=cate_list)


@admin_blue.route('/news_edit_detail', methods=['GET', 'POST'])
def news_edit_detail():
    if request.method == "GET":
        news_id = request.args.get("news_id")
        try:
            news_cate = db.session.query(Category.id, Category.name).all()
            print(news_cate)
            news_obj = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return render_template("admin/news_edit_detail.html", errmsg="新闻获取失败")
        if not news_obj:
            return render_template("admin/news_edit_detail.html", errmsg="新闻不存在")
        return render_template("admin/news_edit_detail.html", news=news_obj.to_dict(), cate=news_cate)

    title = request.form.get("title")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")
    content = request.form.get("content")
    digest = request.form.get("digest")
    news_id = request.form.get("news_id")
    if not all([news_id, digest, title, content, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    try:
        news_obj: News = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")
    if not news_obj:
        return jsonify(errno=RET.NODATA, errmsg="新闻不存在")
    # 上传图片
    try:
        if index_image:
            image_name = image_storage.image_storage(index_image.read())
            news_obj.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="图片上传失败")
    news_obj.title = title
    news_obj.category_id = category_id
    news_obj.content = content

    news_obj.digest = digest
    db.session.commit()

    return jsonify(errno=RET.OK, errmsg="操作成功")


@admin_blue.route('/news_edit')
def news_edit():
    keywords = request.args.get("keywords", "")
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        page = 1
    try:
        # 判断是否有搜索关键字
        filters = []

        if keywords:
            filters.append(News.title.contains(keywords))
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, 10, False)


    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")
    totalPage = paginate.pages
    items = paginate.items
    currentPage = paginate.page
    news_list = []
    for item in items:
        news_list.append(item.to_review_dict())
    data = {
        "totalPage": totalPage,
        "currentPage": currentPage,
        "news_list": news_list
    }
    return render_template("admin/news_edit.html", data=data)


@admin_blue.route('/news_review_detail', methods=["GET", "POST"])
def news_review_detail():
    if request.method == "GET":
        news_id = request.args.get("news_id")
        try:
            news_obj = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return render_template("admin/news_review_detail.html", errmsg="新闻获取失败")
        if not news_obj:
            return render_template("admin/news_review_detail.html", errmsg="新闻不存在")
        return render_template("admin/news_review_detail.html", news=news_obj.to_dict())
    action = request.json.get("action")
    news_id = request.json.get("news_id")
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    if action not in ["accept", "reject"]:
        return jsonify(errno=RET.DATAERR, errmsg="无效操作")
    try:
        news_obj = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")
    if not news_obj:
        return jsonify(errno=RET.NODATA, errmsg="新闻不存在")
    if action == "accept":
        news_obj.status = 0
    else:
        news_obj.status = -1
        news_obj.reason = request.json.get("reason", "")
    return jsonify(errno=RET.OK, errmsg="操作成功")


@admin_blue.route('/news_review')
def news_review():
    keywords = request.args.get("keywords", "")
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        page = 1
    try:
        # 判断是否有搜索关键字
        filters = [News.status != 0]

        if keywords:
            filters.append(News.title.contains(keywords))
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, 2, False)


    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")
    totalPage = paginate.pages
    items = paginate.items
    currentPage = paginate.page
    news_list = []
    for item in items:
        news_list.append(item.to_review_dict())
    data = {
        "totalPage": totalPage,
        "currentPage": currentPage,
        "news_list": news_list
    }
    return render_template("admin/news_review.html", data=data)


@admin_blue.route('/user_list')
def user_list():
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        page = 1
    try:
        paginate = User.query.filter(User.is_admin == False).order_by(User.create_time.desc()).paginate(page, 10, False)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取用户失败")
    totalPage = paginate.pages
    items = paginate.items
    currentPage = paginate.page
    user_list = []
    for item in items:
        user_list.append(item.to_admin_dict())
    data = {
        "totalPage": totalPage,
        "currentPage": currentPage,
        "user_list": user_list
    }

    return render_template("admin/user_list.html", data=data)


@admin_blue.route('/user_count')
def user_count():
    # 总数 日活量 月活人数
    try:
        total_user = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/user_count.html', errmsg="获取总人数失败")
    localtime = time.localtime()
    try:
        # 大于本月1号的0点
        # 获取本月的一号的0点的字符串数据
        # 根据字符串，格式化日期对象
        month_start_time_str = "%s-%s-01" % (localtime.tm_year, localtime.tm_mon)
        month_start_time_date = datetime.datetime.strptime(month_start_time_str, "%Y-%m-%d")

        month_count = User.query.filter(User.last_login >= month_start_time_date, User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/user_count.html', errmsg="获取月活跃人数失败")
    try:
        # 大于本日的0点
        day_start_time_str = "%s-%s-%s" % (localtime.tm_year, localtime.tm_mon, localtime.tm_mday)
        day_start_time_date = datetime.datetime.strptime(day_start_time_str, "%Y-%m-%d")

        day_count = User.query.filter(User.last_login >= day_start_time_date, User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/user_count.html', errmsg="获取月活跃人数失败")
    active_date = []  # 获取活跃的日期
    active_count = []  # 记录活跃的人数

    for i in range(15):
        # 当天开始时间
        begin_date = day_start_time_date - datetime.timedelta(days=i)
        # 当天开始时间的后一天
        end_date = day_start_time_date - datetime.timedelta(days=i - 1)
        active_date.append(begin_date.strftime("%m-%d"))
        everyday_active_count = User.query.filter(User.is_admin == False, User.last_login >= begin_date,
                                                  User.last_login <= end_date).count()
        active_count.append(everyday_active_count)
    active_count.reverse()
    active_date.reverse()
    data = {
        "total_count": total_user,
        "month_count": month_count,
        "day_count": day_count,
        "active_count": active_count,
        "active_date": active_date

    }
    return render_template('admin/user_count.html', data=data)


@admin_blue.route('/index')
@user_login_data
def index():
    data = {
        "user_info": g.user.to_dict() if g.user else ""
    }
    return render_template("admin/index.html", data=data)


@admin_blue.route('/login', methods=['GET', 'POST'])
def admin_login():
    if request.method == "GET":
        if session.get("is_admin"):
            return redirect("/admin/index")
        return render_template("admin/login.html")
    username = request.form.get("username")
    password = request.form.get("password")

    if not all([username, password]):
        return render_template("admin/login.html", errmsg="参数不全")
    try:
        admin = User.query.filter(User.mobile == username, User.is_admin == True).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg="管理员获取失败")

    if not admin:
        return render_template("admin/login.html", errmsg="管理员不存在")
    if not admin.check_passowrd(password):
        return render_template("admin/login.html", errmsg="密码错误")
    session["user_id"] = admin.id
    session["is_admin"] = True
    return redirect("/admin/index")
